package com.dtagri.fjwlw.base;

import java.io.Serializable;

import org.apache.http.Header;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

import com.dtagri.fjwlw.cache.CacheManager;
import com.dtagri.fjwlw.widget.EmptyLayout;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * 与BaseSimpleActivity配合使用
 * 
 * @author wxjn
 * 
 */
public abstract class BaseSimpleFragment extends BaseFragment {

	public void setBaseSimpleActivity(BaseSimpleActivity baseSimpleActivity) {
		this.baseSimpleActivity = baseSimpleActivity;
	}

	protected BaseSimpleActivity baseSimpleActivity;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initView(getView());
		initData();
	}

	@Override
	public void initView(View view) {
		super.initView(view);
		baseSimpleActivity.getmErrorLayout().setOnLayoutClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						initData();
					}
				});
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		return inflateView(getLayoutId());
	}

	protected final AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			if (getCacheKey() == null) {
				baseSimpleActivity.getmErrorLayout().setErrorType(
						EmptyLayout.NETWORK_ERROR);
			} else {
				Serializable serializable = CacheManager.readObject(
						getActivity(), getCacheKey());
				if (serializable == null) {
					baseSimpleActivity.getmErrorLayout().setErrorType(
							EmptyLayout.NETWORK_ERROR);
				} else {
					onSuccess(arg0, arg1, ((String) serializable).getBytes());
				}
			}
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			baseSimpleActivity.getmErrorLayout().setErrorType(
					EmptyLayout.HIDE_LAYOUT);
			if (getCacheKey() != null) {
				CacheManager.saveObject(getActivity(), new String(arg2),
						getCacheKey());
			}
			xOnSuccess(arg2);
		}

	};

	@Override
	public void initData() {
		baseSimpleActivity.getmErrorLayout().setErrorType(
				EmptyLayout.NETWORK_LOADING);
		xInitData();
	}

	protected abstract String getCacheKey();

	protected abstract void xInitData();

	protected abstract void xOnSuccess(byte[] arg2);
}
